package com.mvvmhabit.org.base

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.mvvmhabit.org.R
import com.mvvmhabit.org.utils.DisplayUtil
import java.lang.ref.WeakReference

/**
 * @Date: 2020/10/30 15:06
 * @Author:小妖
 * @Description: 盛装Fragment的一个容器Activity
 */
class ContainerActivity : AppCompatActivity() {

    // 弱引用
    protected var mFragment: WeakReference<Fragment>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        // 适配方案
        DisplayUtil.setCustomDensity(this, application)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_container)
        val fm: FragmentManager = supportFragmentManager
        var fragment: Fragment? = null
        if (savedInstanceState != null) {
            fragment = fm.getFragment(savedInstanceState, FRAGMENT_TAG)
        }
        if (fragment == null) {
            fragment = initFromIntent(intent)
        }
        val trans = supportFragmentManager.beginTransaction()
        trans.replace(R.id.content, fragment)
        trans.commitAllowingStateLoss()
        mFragment = WeakReference(fragment)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        supportFragmentManager.putFragment(outState, FRAGMENT_TAG, mFragment?.get()!!)
    }

    private fun initFromIntent(data: Intent?): Fragment {
        if (data == null) {
            throw RuntimeException("you must provide a page info to display")
        }
        try {
            val fragmentName = data.getStringExtra(FRAGMENT)
            if (fragmentName == null || "" == fragmentName) {
                throw IllegalArgumentException("can not find page fragmentName")
            }
            val fragmentClazz = Class.forName(fragmentName)
            val fragment: Fragment = fragmentClazz.newInstance() as Fragment
            val args = data.getBundleExtra(FRAGMENT_BUNDLE)
            if (args != null) {
                fragment.arguments = args
            }
            return fragment
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        } catch (e: InstantiationException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
        throw RuntimeException("fragment initialization failed!")
    }

    override fun onBackPressed() {
        val fragment = supportFragmentManager.findFragmentById(R.id.content)
        if (fragment != null && fragment is BaseFragment<*, *>) {
            if (!fragment.isBackPressed()) {
                super.onBackPressed()
            }
        } else {
            super.onBackPressed()
        }
    }
}